// cloudfunctions/getUserBankCards/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { userId } = event
    
    if (!userId) {
      return { success: false, message: '用户ID不能为空' }
    }
    
    // 查询用户的银行卡列表，按默认卡优先排序
    const res = await db.collection('user_bank_cards')
      .where({ userId: userId })
      .orderBy('isDefault', 'desc')
      .orderBy('createTime', 'desc')
      .get()
      
    // 处理银行卡号显示（只显示后四位）
    const cards = res.data.map(card => {
      return {
        ...card,
        cardNumberDisplay: `**** **** **** ${card.cardNumber.substring(card.cardNumber.length - 4)}`
      }
    })
    
    return {
      success: true,
      cards: cards
    }
    
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
    return { success: false, message: '获取银行卡列表失败' }
  }
}